#pragma once
#include <pthread.h>
#include "TcpServer.hpp"
#include "signal.h"
#include "Protocol.hpp"
#include "Log.hpp"

#define PORT 8081

class HttpServer {
    public:
        HttpServer(int _port = PORT)
            :port(_port)
            ,svr(nullptr)
            ,stop(false)
        {}
        void InitServer(){
            // 在send时出错会出发sigpipe信号导致进出奔溃，这里对sigpipe进行忽略，后面根据send返回值手动处理发送错误情况
            signal(SIGPIPE, SIG_IGN);
            svr = TcpServer::getInstance(port);
        }
        void Loop () {
            LOG(INFO, "Loop begin");
            int listen_sock = svr->Sock();
            while (!stop) {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(listen_sock, (struct sockaddr*)&peer, &len);
                if (sock < 0) {
                    continue;
                }
                LOG(INFO, "Get a new link"); 
                int * _sock = new int(sock);
                pthread_t tid;
                pthread_create(&tid, nullptr, Entrance::HandlerRequest, _sock);
                pthread_detach(tid);
            }
        }
        ~HttpServer()
        {}
    private:
        int port;
        TcpServer *svr;
        bool stop;
};